'use client'
import React, { useState, useEffect, useContext } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import AuthContext from '../../../context/AuthContext';
import { get, del, post } from '../../../utils/axios'

export default function BlogPostDetail() {
  const router = useRouter()
  const params = useParams()
  const postId = params.id
  const { user, logout } = useContext(AuthContext)
  const [postInfo, setPostInfo] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [deleteLoading, setDeleteLoading] = useState(false)
  const [messages, setMessages] = useState([])
  const [commentText, setCommentText] = useState('')
  const [commentLoading, setCommentLoading] = useState(false)

  useEffect(() => {
    fetchPostData()
  }, [postId])

  useEffect(() => {
    if (postInfo) {
      fetchMessages()
    }
  }, [postInfo])

  // 获取文章详情数据
  const fetchPostData = async () => {
    try {
      setLoading(true)
      setError('')
      const response = await get(`/api/post/${postId}`)
      if (response && response.data) {
        setPostInfo(response.data)
      } else {
        setError('未找到文章')
      }
    } catch (err) {
      console.error('获取文章详情失败:', err)
      setError('获取文章详情失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 获取评论列表
  const fetchMessages = async () => {
    try {
      const response = await get(`/api/message/post/${postId}`)
      if (response && response.data) {
        setMessages(response.data)
      }
    } catch (err) {
      console.error('获取评论列表失败:', err)
      // 不显示错误，因为评论不是核心功能
    }
  }

  // 提交评论
  const handleCommentSubmit = async e => {
    e.preventDefault()

    if (!user) {
      alert('请先登录后再评论')
      return
    }

    if (!commentText.trim()) {
      alert('评论内容不能为空')
      return
    }

    try {
      setCommentLoading(true)
      const response = await post(`/api/message/${postId}`, { content: commentText })
      if (response && response.data) {
        setCommentText('') // 清空评论输入框
        await fetchMessages() // 重新获取评论列表
      }
    } catch (err) {
      console.error('提交评论失败:', err)
      alert('提交评论失败，请重试')
    } finally {
      setCommentLoading(false)
    }
  }

  // 删除评论
  const handleDeleteMessage = async messageId => {
    if (!confirm('确定要删除这条评论吗？')) {
      return
    }

    try {
      const response = await del(`/api/message/${messageId}`)
      if (response && response.data && response.data.success) {
        await fetchMessages() // 重新获取评论列表
      } else {
        alert(response?.data?.message || '删除评论失败')
      }
    } catch (err) {
      console.error('删除评论失败:', err)
      alert('删除评论失败，请重试')
    }
  }

  // 处理删除文章
  const handleDelete = async () => {
    if (!confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
      return
    }

    try {
      setDeleteLoading(true)
      await del(`/api/post/${postId}`)
      // 删除成功后返回博客列表
      router.push('/blog')
    } catch (err) {
      console.error('删除文章失败:', err)
      setError('删除文章失败，请重试')
    } finally {
      setDeleteLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-xl text-gray-600">加载中...</div>
      </div>
    )
  }

  if (error || !postInfo) {
    return (
      <div className="min-h-screen bg-gray-50">
        {/* 导航栏 */}
        <header className="bg-white shadow">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between h-16">
              <div className="flex items-center">
                <Link href="/" className="text-xl font-bold text-indigo-600">
                  我的博客
                </Link>
              </div>
              <div className="flex items-center">
                {user && (
                  <div className="flex items-center space-x-4">
                    <span className="text-gray-700">欢迎, {user.name}</span>
                    <button onClick={logout} className="bg-indigo-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-indigo-700">
                      登出
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </header>

        <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="bg-white shadow-md rounded-lg p-6">
            <h1 className="text-3xl font-bold text-gray-900 mb-4">{error || '未找到文章'}</h1>
            <p className="text-gray-600 mb-6">{error ? '请检查URL或稍后再试' : '您访问的文章可能已被删除或移动'}</p>
            <Link href="/blog" className="inline-flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700">
              返回博客列表
            </Link>
          </div>
        </main>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 导航栏 */}
      <header className="bg-white shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between h-16">
            <div className="flex items-center">
              <Link href="/" className="text-xl font-bold text-indigo-600">
                我的博客
              </Link>
            </div>
            <div className="flex items-center">
              {user && (
                <div className="flex items-center space-x-4">
                  <span className="text-gray-700">欢迎, {user.name}</span>
                  <button onClick={logout} className="bg-indigo-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-indigo-700">
                    登出
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {error && <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">{error}</div>}

        <article className="bg-white shadow-md rounded-lg overflow-hidden">
          <div className="p-6 md:p-8">
            <div className="flex flex-wrap justify-between items-start mb-6">
              <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4 md:mb-0 w-full md:w-auto">{postInfo.title}</h1>
              {user && postInfo.user && postInfo.user.id === user.id && (
                <div className="flex space-x-3 w-full md:w-auto">
                  <a href={`/blog/editor?postId=${postInfo.id}`} className="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                    编辑
                  </a>
                  <button onClick={handleDelete} className="inline-flex items-center px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700" disabled={deleteLoading}>
                    {deleteLoading ? (
                      <span className="flex items-center">
                        <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        删除中...
                      </span>
                    ) : (
                      '删除'
                    )}
                  </button>
                </div>
              )}
            </div>

            <div className="flex items-center text-sm text-gray-500 mb-8">
              <span>作者: {postInfo.user?.name || '未知作者'}</span>
              <span className="mx-2">•</span>
              <span>发布时间: {new Date(postInfo.createdAt || Date.now()).toLocaleDateString('zh-CN')}</span>
            </div>

            <div className="prose prose-lg max-w-none text-gray-700">
              <div className="whitespace-pre-line">{postInfo.content}</div>
            </div>
          </div>
        </article>

        {/* 评论区 */}
        <div className="mt-8 bg-white shadow-md rounded-lg p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-6">评论 ({messages.length})</h2>

          {/* 评论表单 */}
          <div className="mb-8">
            {user ? (
              <form onSubmit={handleCommentSubmit}>
                <div className="mb-4">
                  <textarea value={commentText} onChange={e => setCommentText(e.target.value)} placeholder="写下你的评论..." className="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent" rows={4} disabled={commentLoading} />
                </div>
                <button type="submit" className="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 transition-colors" disabled={commentLoading}>
                  {commentLoading ? '提交中...' : '发表评论'}
                </button>
              </form>
            ) : (
              <div className="p-4 bg-gray-100 rounded-md text-gray-600">
                <Link href="/login" className="text-indigo-600 hover:underline">
                  请先登录
                </Link>{' '}
                后才能发表评论
              </div>
            )}
          </div>

          {/* 评论列表 */}
          <div className="space-y-4">
            {messages.length === 0 ? (
              <p className="text-gray-500 text-center py-4">暂无评论，快来抢沙发吧！</p>
            ) : (
              messages.map(message => (
                <div key={message.id} className="p-4 border border-gray-200 rounded-md">
                  <div className="flex justify-between items-start mb-2">
                    <div className="flex items-center">
                      <span className="font-medium text-gray-800">{message.user?.name || '匿名用户'}</span>
                      <span className="ml-2 text-xs text-gray-500">{new Date(message.createdAt).toLocaleString('zh-CN')}</span>
                    </div>
                    {user && message.user && message.user.id === user.id && (
                      <button onClick={() => handleDeleteMessage(message.id)} className="text-red-500 hover:text-red-700 text-sm">
                        删除
                      </button>
                    )}
                  </div>
                  <p className="text-gray-700">{message.content}</p>
                </div>
              ))
            )}
          </div>
        </div>

        <div className="mt-8">
          <Link href="/blog" className="inline-flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            返回博客列表
          </Link>
        </div>
      </main>
    </div>
  )
}